<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<head th:include="include :: header">
    <style>
        .input-group {
            margin-bottom: 10px;
        }

        .input-box {
            width: 45%;
            display: inline-block;
            margin-right: 5px;
        }

        .remove-btn {
            width: 10%;
            display: inline-block;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content ">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="form-horizontal m-t">
                        <div class="form-group">
                            <label class="col-sm-3 control-label"><span style="color: red">*</span>商品分类：</label>
                            <div class="col-sm-8">
                                <select class="form-control valid" name="category" id="category">
                                    <option value="">请选择商品分类</option>
                                    <option value="0">教材</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label"><span style="color: red">*</span>商品类型：</label>
                            <div class="col-sm-8">
                                <select class="form-control valid" name="typeName" id="typeName">
                                </select>
                            </div>
                        </div>

                        <!--                        <div class="form-group">-->
                        <!--                            <label class="col-sm-3 control-label"><span style="color: red">*</span>商品名称:</label>-->
                        <!--                            <div class="col-sm-8">-->
                        <!--                                <input id="productName" name="productName" placeholder="请输入商品名称"-->
                        <!--                                       class="form-control"-->
                        <!--                                       type="text">-->
                        <!--                            </div>-->
                        <!--                        </div>-->
                        <div class="form-group">
                            <label class="col-sm-3 control-label"><span style="color: red">*</span>商品规格：</label>
                            <div class="col-sm-8" style="display: flex;flex-direction: column;align-items: center;">
                                <div class="wrapper " style="padding: 0px;">
                                    <!--                                    <button id="getValues">获取值</button>-->
                                    <div id="inputContainer">
                                        <!-- 默认的一行输入框 -->

                                    </div>
                                    <!--                                    <pre id="output"></pre>-->
                                </div>

                                <button id="addInput" class="btn  btn-success"
                                        style="width: 200px;margin-top: 20px;margin-left: -72px;">
                                    添加商品
                                </button>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">单位名称:</label>
                            <div class="col-sm-8">
                                <input id="unitName" name="unitName" placeholder="请输入单位名称"
                                       class="form-control"
                                       type="text">
                            </div>
                        </div>

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">年份:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="year" name="year" placeholder="请输入年份"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">订单编号:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="orderNumber" name="orderNumber" placeholder="请输入订单编号"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

                        <div class="form-group">
                            <label class="col-sm-3 control-label">订单开始时间：</label>
                            <div class="col-sm-8">
                                <input id="orderStartTime" name="orderStartTime"
                                       class="form-control" type="text"
                                       placeholder="请输入订单开始时间">
                            </div>
                        </div>

                        <div class="form-group" id="orProd">
                            <label class="col-sm-3 control-label">订单所属省份：</label>
                            <div class="col-sm-8">
                                <input th:value="${orderSpecs.orderProvince}" type="hidden" id="ordprovinceValue"/>
                                <select id="orderProvince"   name="orderProvince" class="form-control"
                                        type="text"></select>

                            </div>
                        </div>
                        <div class="form-group" id="orCityd">
                            <label class="col-sm-3 control-label">订单所属市：</label>
                            <div class="col-sm-8">
                                <input th:value="${orderSpecs.orderCity}" type="hidden" id="ordercityeValue"/>
                                <select id="orderCity"  name="orderCity" th:value="${orderSpecs.orderCity}"
                                        class="form-control" type="text"></select>

                            </div>
                        </div>

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">开票名称:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="billingName" name="billingName" placeholder="请输入开票名称" th:value="${orderSpecs.billingName}"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">纳税识别号:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="billingNumber" name="billingNumber" placeholder="请输入纳税识别号" th:value="${orderSpecs.billingNumber}"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">开户地址:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="billingAddress" name="billingAddress" placeholder="请输入开户地址" th:value="${orderSpecs.billingAddress}"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">开户行账户:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="billingAccountNumber" name="billingAccountNumber"-->
<!--                                       placeholder="请输入开户行账户" class="form-control" th:value="${orderSpecs.billingAccountNumber}"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">开户行邮箱:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="billingMailbox" name="billingMailbox" placeholder="请输入开户行邮箱" th:value="${orderSpecs.billingMailbox}"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">发票审核描述:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="stateMoneyMark" name="stateMoneyMark" placeholder="请输入发票审核描述" th:value="${orderSpecs.stateMoneyMark}"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">发票类型:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <label class="radio-inline"> <input type="radio"-->
<!--                                                                    name="invoiceType" value="纸质发票"/> 纸质发票-->
<!--                                </label> <label class="radio-inline"> <input type="radio"-->
<!--                                                                             name="invoiceType" value="电子发票"/> 电子发票-->
<!--                            </label>-->
<!--                            </div>-->
<!--                        </div>-->
<!--                        <div class="form-group">-->
<!--                            <label class="col-sm-3 control-label">发票地址:</label>-->
<!--                            <div class="col-sm-8">-->
<!--                                <input id="invoiceAddress" name="invoiceAddress" placeholder="请输入发票地址"-->
<!--                                       class="form-control"-->
<!--                                       type="text">-->
<!--                            </div>-->
<!--                        </div>-->

                        <div class="div_3" id="adre">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">收货地址省份：</label>
                                <div class="col-sm-8">
                                    <input type="hidden" style="width: 150px" id="province"
                                           th:value="${orderSpecs.province}"/>
                                    <select name="province" th:value="${orderSpecs.province}" class="form-control" id="provinceValue"
                                            type="text"></select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">收货地址市：</label>
                                <div class="col-sm-8">
                                    <input type="hidden" style="width: 150px" id="city" th:value="${orderSpecs.city}"/>
                                    <select name="city" th:value="${orderSpecs.city}" class="form-control" id="cityValue"
                                            type="text"></select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">收货地址县：</label>
                                <div class="col-sm-8">
                                    <input type="hidden" style="width: 150px" id="district"
                                           th:value="${orderSpecs.county}"/>
                                    <select name="district" class="form-control" type="text" id="districtValue"></select>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">详细地址:</label>
                            <div class="col-sm-8">
                                <input id="address" name="address" placeholder="请输入详细地址"  th:value="${orderSpecs.address}"
                                       class="form-control"
                                       type="text">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">收货人:</label>
                            <div class="col-sm-8">
                                <input id="recipient" name="recipient" placeholder="请输入收货人" th:value="${orderSpecs.recipient}"
                                       class="form-control"
                                       type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">收货人联系电话:</label>
                            <div class="col-sm-8">
                                <input id="telephone" name="telephone" placeholder="请输入收货人联系电话" th:value="${orderSpecs.telephone}"
                                       class="form-control"
                                       type="text">
                            </div>
                        </div>

                        <div class="form-group" >
                            <label class="col-sm-3 control-label">是否包邮：</label>
                            <div class="col-sm-8">

                                <select id="freeShipping"  name="freeShipping" class="form-control"
                                        type="text">
                                    <option value="0">不包邮</option>
                                    <option value="1">包邮</option>
                                </select>

                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-8 col-sm-offset-3" style="display: flex;justify-content: space-evenly;">
                                <button style="width: 150px;margin-left: -68px;" class="btn btn-primary"
                                        id="getValues">提交
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div th:include="include::footer"></div>
<script src="/js/jquery.citys.js"></script>
<script src="//s.xlongwei.com/res/js/My97DatePicker/WdatePicker.js"></script>
<!--	<script type="text/javascript" src="/js/webJs/jzweb/order/edit.js">-->
<script>
    var bookList = [], selectDate = []
    var dataList = JSON.parse(sessionStorage.getItem('order'))
    $(function () {
        getProductType()
        $('#orderStartTime').val(dataList.orderStartTime)
        $('#year').val(dataList.year)
        // $('#orderCity').val(dataList.orderCity)
        // $('#orderProvince').val(dataList.orderProvince)
        $('#freeShipping').val(dataList.freeShipping)
        $('#unitName').val(dataList.unitName)
        $('#category').val(dataList.category)
        // $('#productName').val(dataList.productName)
        $('#billingName').val(dataList.billingName)
        $('#billingNumber').val(dataList.billingNumber)
        $('#billingAddress').val(dataList.billingAddress)
        $('#billingAccountNumber').val(dataList.billingAccountNumber)
        $('#billingMailbox').val(dataList.billingMailbox)
        $('#stateMoneyMark').val(dataList.stateMoneyMark)
        $('#invoiceAddress').val(dataList.invoiceAddress)
        $('input[name="invoiceType"]').each(function () {
            if ($(this).val() === dataList.invoiceType) {
                $(this).prop('checked', true);
            }
        });
        $('#typeName').val(dataList.typeId)
        //省市区联动
        $('#adre').citys({
            province: $("#province").val(),
            city: $("#city").val(),
            district: $("#district").val(),
            onChange: function (info) {
            }
        });
    });

    $.get(
        '/jzweb/examinationCost/userProvinceSel',
        {type: 0},
        function (data) {
            let str = '';
            let orpro = $("#orcityCopy").val();
            if (data.code == 0) {
                str = `<option value="">--请选择省份--</option>`;
                data.data.forEach(function (v) {
                    if (orpro == v.name) {
                        str += `<option value="${v.name}" selected>${v.name}</option>`
                    }
                    str += `<option value="${v.name}">${v.name}</option>`
                })
            }
            $("#orderProvince").html(str)
            $('#orderProvince').val($('#ordprovinceValue').val())
        }
    )

    $.get(
        '/jzweb/examinationCost/userProvinceSel',
        {type: 1},
        function (data) {
            let str = '';
            let orpro = $("#orcityCopy").val();
            if (data.code == 0) {
                str = `<option value="">--请选择城市--</option>`;
                data.data.forEach(function (v) {
                    if (orpro == v.name) {
                        str += `<option value="${v.name}" selected>${v.name}</option>`
                    }
                    str += `<option value="${v.name}">${v.name}</option>`
                })
            }
            $("#orderCity").html(str)
            $("#orderCity").val($('#ordercityeValue').val())
        }
    )

    layui.use('laydate', function () {

        var laydate = layui.laydate;

        laydate.render({
            elem: '#orderStartTime'
            , type: 'datetime'
        });

    })

    function getProductType() {
        $.ajax({
            cache: true,
            type: "POST",
            url: '/jzweb/productType/list',
            data: {
                current: 1,
                size: 10000,
            },// 你的formid
            contentType: "application/x-www-form-urlencoded",
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.code == 0) {
                    $("#typeName").append('<option value="">请选择</option>');
                    for (var i = 0; i < data.data.records.length; i++) {
                        var a = data.data.records[i].typeName
                        if (data.data.records[i].state == 0) {
                            $("#typeName").append("<option value='" + data.data.records[i].id + "'>" + a + "</option>");
                        }
                    }
                } else {
                    $("#typeName").append('<option value="">暂无数据</option>');
                }
            }
        });
        $.ajax({
            cache: true,
            type: "POST",
            url: '/jzweb/bookConfig/list',
            data: {
                current: 1,
                size: 10000,
            },// 你的formid
            contentType: "application/x-www-form-urlencoded",
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.code == 0) {
                    bookList = data.data.records
                    selectDate = data.data.records
                    $('.key').append('<option value="">请选择</option>');
                    for (var i = 0; i < data.data.records.length; i++) {
                        var a = data.data.records[i].bookName
                        $('.key').append("<option value='" + data.data.records[i].id + "'>" + a + "</option>");
                    }
                } else {
                    $('.key').append('<option value="">暂无数据</option>');
                }
            }
        });

    }

    // 默认数据
    const defaultData = JSON.parse(dataList.specs);

    // 动态添加输入框和删除按钮的脚本
    $(document).ready(function () {

        $('.discount').on('input', function() {
            // 获取当前值
            var value = $(this).val();

            // 使用正则表达式检查是否超过两位小数
            if (value.includes('.') && value.split('.')[1].length > 2) {
                // 如果超过两位小数，截取到两位小数
                var newValue = parseFloat(value).toFixed(2);
                $(this).val(newValue);
            }
        });

    //     <!--                    <select class="form-control input-box discount" name="discount" style="margin-left: 10px">-->
    // <!--                                                <option value="1">原价</option>-->
    //     <!--                                                <option value="0.1">一折</option>-->
    //     <!--                                                <option value="0.2">二折</option>-->
    //     <!--                                                <option value="0.3">三折</option>-->
    //     <!--                                                <option value="0.4">四折</option>-->
    //     <!--                                                <option value="0.5">五折</option>-->
    //     <!--                                                <option value="0.6">六折</option>-->
    //     <!--                                                <option value="0.7">七折</option>-->
    //     <!--                                                <option value="0.8">八折</option>-->
    //     <!--                                                <option value="0.9">九折</option>-->
    //     <!--                     </select>-->

        // 定义一个模板字符串，用于生成输入框和删除按钮
        const inputTemplate = `
                <div class="input-group" style="display: flex;margin-top: 10px;align-items: center;">
                <select class="form-control input-box key" name="typeName">
                                            </select>
                    <input type="number" min="0"  class="form-control input-box num" name="number" placeholder="数量" style="margin-left: 10px;width: 190px">

                    <button class="btn btn-danger remove-btn" style="margin: 0px;width: 190px">删除</button>
                </div>
            `;
        // 渲染默认数据
        renderInputBoxes(defaultData);

        // 绑定点击事件到添加按钮
        $('#addInput').on('click', function () {
            const $inputGroup = $(inputTemplate);
            $('#inputContainer').append($inputGroup);

            // 填充 <select> 元素
            fillSelectOptions($inputGroup.find('.key'));

            // 绑定删除按钮的点击事件
            $inputGroup.find('.remove-btn').on('click', function () {
                $(this).closest('.input-group').remove();
            });
            $('.discount').on('input', function() {
                // 获取当前值
                var value = $(this).val();

                // 使用正则表达式检查是否超过两位小数
                if (value.includes('.') && value.split('.')[1].length > 2) {
                    // 如果超过两位小数，截取到两位小数
                    var newValue = parseFloat(value).toFixed(2);
                    $(this).val(newValue);
                }
            });
        });

        //计算



        function fillSelectOptions($select) {
            $select.append('<option value="">请选择</option>');
            console.log(bookList)
            for (var i = 0; i < bookList.length; i++) {
                var a = bookList[i].bookName
                $select.append("<option value='" + bookList[i].id + "'>" + a + "</option>");
            }
        }

        // 获取所有输入框的值，并构造对象数组
        $('#getValues').on('click', function () {
            const values = [];

            // 遍历所有的输入框组
            $('.input-group').each(function () {
                const $group = $(this);
                const key = $group.find('.key').val().trim();
                const num = $group.find('.num').val().trim();
                if (key) {
                    values.push({'spec': key, 'money': 0, 'number': num, 'discount': 0});
                }
            });

            // 显示收集到的对象数组
            // $('#output').text(JSON.stringify(values, null, 2));
            if (!$('#category').val()) {
                layer.msg("请选择商品分类");
                return false;
            }
            if (!$('#typeName').val()) {
                layer.msg("请选择商品类型");
                return false;
            }
            // if (!$('#productName').val()) {
            //     layer.msg("请输入商品名称");
            //     return false;
            // }
            if (values.length < 1) {
                layer.msg("请至少输入一种商品规格");
                return false;
            }
            $.ajax({
                cache: true,
                type: "POST",
                url: '/jzweb/orderSpecs/update',
                data: JSON.stringify({
                    orderType:1,
                    id: dataList.id,
                    specs: JSON.stringify(values),
                    typeId: $('#typeName').val(),
                    billingAccountNumber: $('#billingAccountNumber').val(),
                    billingAddress: $('#billingAddress').val(),
                    billingMailbox: $('#billingMailbox').val(),
                    billingName: $('#billingName').val(),
                    billingNumber: $('#billingNumber').val(),
                    category: $('#category').val(),
                    invoiceAddress: $('#invoiceAddress').val(),
                    invoiceType: $('input[name="invoiceType"]:checked').val(),
                    // productName: $('#productName').val(),
                    stateMoneyMark: $('#stateMoneyMark').val(),
                    province: $('#provinceValue').val(),
                    city: $('#cityValue').val(),
                    county: $('#districtValue').val(),
                    orderNumber:$('#orderNumber').val(),
                    unitName:$('#unitName').val(),
                    year:$('#year').val(),
                    orderProvince:$('#orderProvince').val(),
                    orderCity:$('#orderCity').val(),
                    freeShipping:$('#freeShipping').val(),
                    orderStartTime:$('#orderStartTime').val(),
                    recipient:$('#recipient').val(),
                    telephone:$('#telephone').val(),
                    address:$('#address').val()
                }),// 你的formid
                contentType: "application/json",
                async: false,
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.code == 0) {
                        parent.layer.msg("操作成功");
                        parent.reLoad();
                        var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                        parent.layer.close(index);
                    } else {
                        parent.layer.alert(data.msg);

                    }
                }
            });


        });
        // 确保删除按钮的事件绑定在每次添加新输入框后仍然有效
        $(document).on('click', '.remove-btn', function () {
            $(this).closest('.input-group').remove();
        });

        // 渲染输入框
        function renderInputBoxes(data) {

            data.forEach(item => {
                // const keys = Object.keys(item);
                const key = item.spec;
                const value = item.money;
                const num = item.number;
                const discount = item.discount

                const $inputGroup = $(inputTemplate);
                $inputGroup.find('.key').val(key);
                $inputGroup.find('.value').val(value);
                $inputGroup.find('.discount').val(discount);
                $inputGroup.find('.num').val(num);
                $inputGroup.find('.key').append('<option value="">请选择</option>');
                for (var i = 0; i < bookList.length; i++) {
                    var a = bookList[i].bookName
                    $inputGroup.find('.key').append("<option value='" + bookList[i].id + "'>" + a + "</option>");
                }
                $inputGroup.find('.key').val(key);
                $('#inputContainer').append($inputGroup);

                // 绑定删除按钮的点击事件
                $inputGroup.find('.remove-btn').on('click', function () {
                    $(this).closest('.input-group').remove();
                });
            });

        }
    });
</script>
</body>
</html>
